<script setup lang="ts">
import { computed } from 'vue'
import BlockItem from '@/components/BlockItem/BlockItem.vue'
import EChart from '@/components/EChart/EChart.vue'

const props = withDefaults(
  defineProps<{
    title?: string
    name?: string
    data?: number[]
    unit?: string
    color?: [string, string]
  }>(),
  {
    title: '',
    name: '',
    data: () => {
      const rand = () => +(Math.random() * 1000 + 1000).toFixed(2)
      return Array(12)
        .fill(1)
        .map(() => rand())
    },
    unit: '吨',
    color: () => ['rgba(19, 56, 144, 1)', 'rgba(109, 162, 239, 1)'],
  },
)

const defaultNumber = inject<(number: string | number | undefined, string?: string, useFormat?: boolean) => string>('defaultNumber')
const chartOption = computed(() => {
  const yAxisData = Array(12)
    .fill(1)
    .map((_v, i) => `${i + 1}月`)
  yAxisData.reverse()

  const seriesData = props.data.slice()
  seriesData.reverse()

  return {
    tooltip: {
      trigger: 'axis',
      valueFormatter: (value: any) => `${defaultNumber ? defaultNumber(value) : ''} ${props.unit}`,
    },
    xAxis: {
      type: 'value',
      name: props.unit,
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: 'rgba(183, 200, 235, 0.2)',
        },
      },
    },
    yAxis: {
      type: 'category',
      data: yAxisData,
    },
    textStyle: {
      color: '#899DBF',
    },
    grid: {
      containLabel: true,
      left: '2%',
      right: '14%',
      bottom: '8%',
      top: '4%',
    },
    series: [
      {
        type: 'bar',
        name: toValue(props.name),
        barWidth: 6,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              {
                offset: 0,
                color: props.color[0],
              },
              {
                offset: 1,
                color: props.color[1],
              },
            ],
          },
        },
        data: seriesData,
      },
    ],
  }
})
</script>

<template>
  <BlockItem
    class="comprehensive-analysis-of-key-indicators"
    :title="title"
  >
    <slot />
    <EChart :option="chartOption" height="24vh" />
  </BlockItem>
</template>
